<?php
/**
 * 微信 - 分享视频
 *
 */

namespace App\Http\Controllers\OpenWechat;


use App\Http\Controllers\ApiController;

use App\Http\Requests\OpenWechat\VideoShareStoreRequest;
use App\Models\OpenWechat\Authorizer;
use App\Models\OpenWechat\ScanEvent;
use App\Services\OpenWechat\MaterialSave;
use App\Services\OpenWechat\QrCode;

use Illuminate\Http\UploadedFile;
use Intervention\Image\ImageManagerStatic;

class VideoShareController extends ApiController
{

    private $try_count = 0;

    const MAX_TRY_COUNT = 3;

    /**
     * @param VideoShareStoreRequest $request
     *
     * @return array|mixed
     * @throws \App\Exceptions\ApiException
     * @link https://www.easywechat.com/docs/master/zh-CN/basic-services/media
     */
    public function store(VideoShareStoreRequest $request)
    {
        /** @var Authorizer $authorizer */
        $authorizer = Authorizer::findByAppId($request->appid);

        $this->checkItemExist($authorizer, 'appid');

        $temp_path = $this->tempSaveVideo($request->video);

        $material = $this->tryUploadMaterial($authorizer, $temp_path);

        $event_reply = $this->createNewEventReply($authorizer, $material['media_id']);

        $qr_code_url = (new QrCode)->tempUrl($request->appid, $event_reply->getSceneValue());

        return $this->responseByQrCodeType($qr_code_url, $request->code_type);
    }

    /**
     * @param $authorizer
     * @param $media_id
     * @return mixed|ScanEvent
     */
    private function createNewEventReply(Authorizer $authorizer, $media_id)
    {
        $event_reply = (new ScanEvent())->create([
            'type'  => ScanEvent::TYPE_REPLY_VIDEO,
            'value' => $authorizer->id,
            'data'  => [
                'media_id' => $media_id
            ]
        ]);

        return $event_reply;
    }


    /**
     * @param $authorizer
     * @param $material_path
     *
     * @return \EasyWeChat\Kernel\Support\Collection
     * @throws \App\Exceptions\ApiException
     */
    private function tryUploadMaterial($authorizer, $material_path)
    {
        try {
            $material = (new MaterialSave($authorizer))->uploadTempVideo($material_path);
            @unlink($material_path);
            return $material;
        } catch (\Exception $exception) {
            if ($this->try_count++ < self::MAX_TRY_COUNT) {
                return $this->tryUploadMaterial($authorizer, $material_path);
            }
            @unlink($material_path);
            logger('wechat video material upload failed: ' . $exception->getMessage());
            $this->checkOperateSuccess(false, trans('open_wechat.notice_video') . $exception->getMessage());
        }
    }

    /**
     * @param string $qr_code_url
     * @param string $code_type
     * @return array|mixed
     */
    private function responseByQrCodeType($qr_code_url, $code_type)
    {
        switch ($code_type) {
            case 'text' :
                return $this->response(compact('qr_code_url'));

            case 'png' :
            default :
                $qr_code = ImageManagerStatic::make($qr_code_url);
                return $qr_code->response('png');
        }
    }

    /**
     * @param UploadedFile $video
     * @return string
     */
    private function tempSaveVideo(UploadedFile $video)
    {
        $temp_path = storage_path('wx_share_video.' . time() . '.mp4');

        copy($video->getRealPath(), $temp_path);

        return $temp_path;
    }

}
